package MWClient;

import java.io.*;
import java.net.*;

/**
 * <pre>
 * @Package : MWClient
 * @File    : ClientManager.java
 * <pre>
 *
 * @Author  : 차재우
 * @Date    : 2013. 7. 22.
 * @Version :
 */
public class ClientManager {
	private String ip = null;
	private int port = 0;

	private Socket socket = null;
	
	/**
	 * <pre>
	 * @Comment : 생성자
	 * <pre>
	 *
	 * @param ip
	 * @param port
	 */
	public ClientManager(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}
	
	/**
	 * <pre>
	 * @Comment : 서버 접속 실패시 재접속
	 * <pre>
	 *
	 * @Method  : ReConnect
	 * @return 접속 성공 여부
	 * @throws IOException
	 */
	private boolean ReConnect() throws IOException {
		if(this.socket == null)
		{
			try {
				this.socket = new Socket(ip, port);
			} catch (IOException e) {
				return false;
			}
		}
		return true;
	}

	/**
	 * <pre>
	 * @Comment : 클라이언튼 시작 루틴
	 * <pre>
	 *
	 * @Method  : StartClient
	 * @throws IOException
	 */
	public void StartClient() throws IOException {
		try {
			if(this.socket == null)
				this.socket = new Socket(ip, port);
		} catch (IOException e) {
			this.socket = null;
		}
		
		while(this.socket == null) {
			ReConnect();
			
			try {
				Thread.sleep(5 * 1000);
				System.out.println("Try to reconnect.");
			} catch (InterruptedException e) {
				e.printStackTrace();
				
			}
		}
		
		try {
			if(this.socket.isConnected()) {
				System.out.println("Connected to the server...ok!");

				Thread sender = new Thread(new ClientSender(socket));
				Thread receiver = new Thread(new ClientReceiver(socket));

				sender.start();
				receiver.start();
			}
		} catch (Exception e) {
			System.out.println("Socket failed.");
		}
	}
}
